/*
 * @Author: your name
 * @Date: 2020-11-16 14:13:26
 * @LastEditTime: 2020-12-03 18:21:12
 * @LastEditors: Please set LastEditors
 * @Description: 对 Product 的处理
 * @FilePath: \contoso-book-app\src\api\service\product.js
 */

import LC from 'leancloud-storage';


/**
 * @description: 添加一个新商品
 * @param {*} title   ：商品标题
 * @param {*} price   ：这个必须是数字类型
 * @param {*} image   ：要上传的图片
 * @param {*} description   ： 商品描述
 * @return {*}
 */
let create = (title, price = 0.0, image = '', description = '') => {
  return new Promise((resolve, reject) => {
    let Product = LC.Object.extend('Product');   // 创建 Product 对象
    let product = new Product();                 // 实例化 product
    let currentUser = LC.User.current();         // 获取当前用户
    let name = image.name;
    let imageFile = new LC.File(name, image);    // 创建(上传)文件对象
    product.set('title', title);
    product.set('price', price);
    product.set('description', description);
    product.set('owner', currentUser);
    product.set('image', imageFile);
    // console.log(product);
    product
      .save()
      .then(resp => {
        console.log("Created a product: ", resp);
        resolve(resp);                         // 操作成功，返回
      }, error => {
        console.log(JSON.stringify(error));
        reject(JSON.stringify(error))          // 操作失败
      })
      .catch(error => {
        console.log(JSON.stringify(error));
        reject(JSON.stringify(error))          // 操作失败
      });
  });
};

/**
 * @description: 获取全部的 Product
 * @param {*}
 * @return {*}
 */
let getProducts = (skip = 0, limit = 20) => {
  return new Promise((resolve, reject) => {
    let productQuery = new LC.Query('Product');
    productQuery
      // .select(['-description'])
      .include('owner', 'image')
      // 按 createdAt 降序排列
      .descending('createdAt')
      .skip(skip)
      .limit(limit)
      .find()
      .then(products => {
        console.log(products);
        resolve(products);
      }).catch(error => {
        reject(error);
      });
  });
};


/**
 * @description: 按ID查询一个商品
 * @param {*} id
 * @return {*}
 */
let getProductById = (id) => {
  return new Promise((resolve, reject) => {
    let productQuery = new LC.Query('Product');

    // get 方法，通过 objectId 获取对象
    productQuery.include('owner', 'image')
      .get(id)
      .then(prod => {
        console.log(prod.toJSON);
        resolve(prod);
      }).catch(error => {
        console.log(error);
        reject(error);
      });
  });
};

function deleteProductById(id) {
  let product = LC.Object.createWithoutData('Product', id);
  return new Promise((resolve, reject) => {
    product.destroy()
      .then(resp => {
        console.log("deleted, ", resp);
        resolve(resp);
      })
      .catch(error => {
        console.log(error);
        reject(error);
      });
  });
};


let getProductCount = () => {
  let productQuery = new LC.Query('Product');
  return new Promise((resolve, reject) => {
    productQuery.count()
      .then(count => {
        console.log("count: ", count);
        resolve(count);
      })
      .catch(error => {
        console.log(error);
        reject(error);
      });
  });

};

export default {
  create,
  getProducts,
  getProductById,
  deleteProductById,
  getProductCount,
}

